#!/bin/bash
# Programme de démarrage de « Sous titrage auto.app » (Mac).
#  - au premier lancement : copie l'application dans le dossier Applications ;
#  - si les composants manquent ou après une mise à jour : ouvre la fenêtre d'installation ;
#  - sinon : lance le logiciel.
APPDIR="$(cd "$(dirname "$0")/../.." && pwd)"
RES="$APPDIR/Contents/Resources/app"
ROOT="$HOME/Library/Application Support/SousTitrageAuto/runtime"
PY="$ROOT/python/bin/python3"
PYREL="20251014"
PYVER="3.12.12"
if [ "$(uname -m)" = "arm64" ]; then ARCH="aarch64-apple-darwin"; else ARCH="x86_64-apple-darwin"; fi
PYURL="https://github.com/astral-sh/python-build-standalone/releases/download/$PYREL/cpython-$PYVER+$PYREL-$ARCH-install_only.tar.gz"

alert() {
  /usr/bin/osascript -e "display alert \"Sous titrage auto\" message \"$1\" as critical buttons {\"OK\"}" >/dev/null 2>&1
}
notify() {
  /usr/bin/osascript -e "display notification \"$1\" with title \"Sous titrage auto\"" >/dev/null 2>&1
}

# 1. L'application doit être dans « Applications » (sinon macOS la lance depuis un dossier temporaire)
case "$APPDIR" in
  /Applications/*|"$HOME/Applications/"*) ;;
  *)
    DEST="/Applications"
    [ -w "$DEST" ] || { DEST="$HOME/Applications"; mkdir -p "$DEST"; }
    TARGET="$DEST/Sous titrage auto.app"
    rm -rf "$TARGET.tmp"
    if /usr/bin/ditto "$APPDIR" "$TARGET.tmp"; then
      /usr/bin/xattr -dr com.apple.quarantine "$TARGET.tmp" 2>/dev/null
      rm -rf "$TARGET" && mv "$TARGET.tmp" "$TARGET"
      /usr/bin/open -n "$TARGET"
      exit 0
    fi
    alert "Impossible de copier l'application dans le dossier Applications. Faites-la glisser vous-même dans Applications, puis ouvrez-la depuis là."
    exit 1
    ;;
esac

# 2. Composants (Python privé, bibliothèques, FFmpeg, modèle) : installés ou à jour ?
APPV="$(cat "$RES/VERSION" 2>/dev/null)"
if [ -x "$PY" ] && grep -q "\"version\": \"$APPV\"" "$ROOT/installed.json" 2>/dev/null; then
  cd "$RES" && exec "$PY" -m sta.launcher
fi

# une ancienne version encore ouverte est arrêtée avant la mise à jour
[ -x "$PY" ] && (cd "$RES" && "$PY" -m sta.launcher --stop >/dev/null 2>&1)
mkdir -p "$ROOT" || { alert "Impossible de créer le dossier des composants."; exit 1; }
if [ ! -x "$PY" ] || ! "$PY" -c "import tkinter" >/dev/null 2>&1; then
  notify "Préparation de l'installation…"
  TMP="$ROOT/python.tar.gz"
  if ! /usr/bin/curl -fsSL --retry 3 -o "$TMP" "$PYURL"; then
    alert "Le téléchargement a échoué. Vérifiez votre connexion Internet, puis rouvrez Sous titrage auto."
    exit 1
  fi
  rm -rf "$ROOT/python" && tar -xzf "$TMP" -C "$ROOT" && rm -f "$TMP"
  if ! "$PY" -c "import tkinter" >/dev/null 2>&1; then
    alert "Les composants téléchargés sont incomplets. Rouvrez Sous titrage auto pour réessayer."
    exit 1
  fi
fi
cd "$RES" && exec "$PY" -m sta.setup_gui --root "$ROOT" --app "$RES" --launch "/usr/bin/open -n \"$APPDIR\""
